package cn.chendd.shiro.examples.commponent;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;

public class MyRedisCacheManager implements CacheManager , Serializable {

    private static final long serialVersionUID = -953432295446974722L;

    private transient static Logger log = LoggerFactory.getLogger(MyRedisCacheManager.class);

    private transient RedisTemplate<Object, Object> redisTemplate;

    public MyRedisCacheManager() {
        System.err.println("MyRedisCacheManager.MyRedisCacheManager");
    }

    @Override
    public <K, V> Cache<K, V> getCache(String name) throws CacheException {
        if (!StringUtils.hasText(name)) {
            throw new IllegalArgumentException("Cache name cannot be null or empty.");
        }
        log.info("redis cache manager get cache name is :{}", name);
        Cache cache = (Cache) redisTemplate.opsForValue().get(name);
        if (cache == null) {
            cache = new MyRedisCache(redisTemplate);
            redisTemplate.opsForValue().set("shiro-cache-" + name, cache);
        }
        return cache;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public RedisTemplate<Object, Object> getRedisTemplate() {
        return redisTemplate;
    }
}
